﻿using System;
using System.Web;
using System.Collections.Specialized;
using System.Reflection;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.IO;
using System.Configuration;
using System.Text;
using System.Data;
using System.Web.SessionState;

/// <summary>
/// Handler请求的基类 用此类动态调用请求的方法
/// 业务核心转发类
/// 2013-07-14
/// </summary>
public class HandlerBase : IHttpHandler, IRequiresSessionState
{
    /// <summary>
    /// 指定过来的http请求类型  主要指定action方法名称的接收方式 get 或者 post 
    /// </summary>
    protected NameValueCollection _httpReuqestString = HttpContext.Current.Request.QueryString;
    protected NameValueCollection _httpRequestForm = HttpContext.Current.Request.Form;
    protected HttpCookieCollection _httpCookies = HttpContext.Current.Request.Cookies;

    /// <summary>
    /// 指定返回头
    /// </summary>
    protected string _contentType = "text/plain";

    /// <summary>
    /// 指定接收action方法的参数名称
    /// </summary>
    protected string _actionName = "action";

    //获取当前的http context
    protected HttpContext Context
    {
        get
        {
            return HttpContext.Current;
        }
    }

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = this._contentType;

       

        try
        {
            //动态调用方法 当然  你还可以在这里加上是否为同域名请求的判断
            this.DynamicMethod();
        }
        catch (AmbiguousMatchException amEx)
        {
            //LogBusiness.ExceptionLog((int)LogFlag.手机站前台, (int)ExceptionLog.Ajax异常, "", "根据该参数" + amEx.Message + "找到了多个方法", MemberIDPlus, BasePage.GetClientIP());
            this.PrintErrorJson(string.Format("根据该参数{0}找到了多个方法", amEx.Message));

        }
        catch (ArgumentException argEx)
        {
            //LogBusiness.ExceptionLog((int)LogFlag.手机站前台, (int)ExceptionLog.Ajax异常, "", "参数异常" + argEx.Message, MemberIDPlus, BasePage.GetClientIP());
            this.PrintErrorJson("参数异常" + argEx.Message);

        }
        catch (ApplicationException apEx)
        {
            //LogBusiness.ExceptionLog((int)LogFlag.手机站前台, (int)ExceptionLog.Ajax异常, "", "程序异常" + apEx.Message, MemberIDPlus, BasePage.GetClientIP());
            this.PrintErrorJson("系统繁忙请稍后重试");//"程序异常" + apEx.Message

        }

    }

    public string IsNullToString(string form)
    {
        return form == null ? "" : form.ToString();
    }
    #region 动态调用方法
    /// <summary>
    /// 动态调用方法
    /// </summary>
    private void DynamicMethod()
    {
        //根据指定的请求类型获取方法名
        string action = this._httpReuqestString[this._actionName];

        if (action != "DtToJson")
        {
            //判断登录状态
            HttpCookie ck = this.Context.Request.Cookies["LoginInfo"];
            //if (ck != null)
            //{

            //}
            //else
            //{
            //    this.Context.Response.Redirect(this.Context.Server.HtmlEncode(this.Context.Request.ApplicationPath) + "LoginOverTime.aspx");
            //}

            if (!string.IsNullOrEmpty(action))
            {
                //获取方法的实例  非静态 需要Public访问权限 忽略大小写
                MethodInfo methodInfo = this.GetType().GetMethod(action, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
                if (methodInfo != null)
                {
                    //调用方法
                    methodInfo.Invoke(this, null);
                }
                else
                {
                    throw new ApplicationException(string.Format("没有找到方法{0}", action));
                }
            }
            else
            {
                throw new ArgumentNullException("没有找到调用方法参数或者方法名为空");
            }
        }
    }
    #endregion

    #region 打印Json的相关处理
    protected void Print(string msg)
    {
        Context.Response.Write(msg);
        Context.Response.End();
    }
    /// <summary>
    /// 打印遇到异常的json
    /// </summary>
    /// <param name="msg"></param>
    protected void PrintErrorJson(string info)
    {
        this.PrintJson("0", info);
    }

    /// <summary>
    /// 打印成功处理的json
    /// </summary>
    /// <param name="msg"></param>
    protected void PrintSuccessJson(string info)
    {
        this.PrintJson("1", info);
    }

    /// <summary>
    /// 打印json
    /// </summary>
    /// <param name="state"></param>
    /// <param name="msg"></param>
    protected void PrintJson(string state, string info)
    {
        this.Context.Response.Write("{\"status\":\"" + state + "\",\"info\":\"" + info + "\"}");
        this.Context.Response.End();
    }
    #endregion

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
   


    /// <summary>
    /// 取得Request的string值，任何错误均返回""，Form优先于QueryString被取出
    /// </summary>
    /// <param name="key">键名</param>
    /// <returns>键值</returns>
    public string RequestString(object key)
    {
        if (HttpContext.Current.Request.Form[key.ToString()] != null)
        {
            return HttpContext.Current.Request.Form[key.ToString()].ToString();
        }
        if (HttpContext.Current.Request.QueryString[key.ToString()] != null)
        {
            return HttpContext.Current.Request.QueryString[key.ToString()].ToString();
        }
        return "";
    }

    /// <summary>
    /// 获取IP
    /// </summary>
    /// <returns></returns>
    public string GetClientIP()
    {
        string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (null == result || result == String.Empty)
        {
            result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }
        if (null == result || result == String.Empty)
        {
            result = HttpContext.Current.Request.UserHostAddress;
        }
        return result;
    }
}
